package com.nowcoder.community.controller.advice;

import com.nowcoder.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice(annotations = Controller.class)//该注解只扫描带有controller注解的Bean
public class ExceptionAdvice {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler({Exception.class})//所有异常都用该方法处理
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.error("服务器发生异常：" + e.getMessage());//打日志：服务器出错啦！
        for(StackTraceElement element : e.getStackTrace()){//出错的栈信息记录下来
            logger.error(element.toString());
        }

        //如果浏览器希望服务器响应的是网页，那就重定向到500错误页面
        //如果希望返回的是异步信息，就返回字符串（格式是JSON字符串，页面可以转成JSON）
        String xRequestedWith = request.getHeader("x-requested-with");//请求方式
        if("XMLHttpRequest".equals(xRequestedWith)){//异步请求
            response.setContentType("application/plain;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(CommunityUtil.getJSONString(1,"服务器异常"));
        }else{//普通请求
            response.sendRedirect(request.getContextPath()+"/error");//重定向到500错误页面
        }

    }
}

